﻿package com.d4p.custom.customContextMenu
{
	import flash.display.Sprite;
	import flash.events.ContextMenuEvent;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	import flash.ui.ContextMenu;
	import flash.ui.ContextMenuBuiltInItems;
	import flash.ui.ContextMenuItem;

	public class CustomContextMenu extends Sprite
	{
		static private var _contextMenuInstance:CustomContextMenu;
		
		private var _contextMenu:ContextMenu;
		
		public function CustomContextMenu(singletonEnforcer:SingletonEnforcer){}
		
		public static function getContextMenu():CustomContextMenu
		{
			if(CustomContextMenu._contextMenuInstance == null){
				CustomContextMenu._contextMenuInstance = new CustomContextMenu(new SingletonEnforcer());
			}
			return CustomContextMenu._contextMenuInstance;
		}
		
		///----------------contextMenu create
		public function contextMenuCreate(object:Object):void
		{
			_contextMenu = new ContextMenu();
			removeDefaultItems();                 // remove contextMenuItem
			addCustomMenuItems();				  // create customMenuItem
			
			object.contextMenu = _contextMenu;
			
		}
		private function removeDefaultItems():void
		{
			_contextMenu.hideBuiltInItems();
			var defaultItems:ContextMenuBuiltInItems = _contextMenu.builtInItems;
			
			defaultItems.print = false;    // current frame print function.
		}
		
		private var _item:Array;
		public function addCustomMenuItems($itemName:Array):void
		{
			if(_item == null)	 	_item 		= new Array();
			if(_itemName == null)	_itemName 	= new Array();
			
			for(var i:int = 0 ; i < $item.length ; i++){
				_item[i] 		= new ContextMenu($item[i], true, true, false);
				_contextMenu.customItems.push(_item[i]);
				
				/////event.
				_item[i].addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, 	itemSelectHandler);
			}
		}
		private function itemSelectHandler(e:ContextMenuEvent):void
		{
			dispatchEvent(new CustomContextMenuEvent(e.type, CustomContextMenuEvent.CUSTOM_CONTEXT_EVENT));
		}
	}
}

//singletonPattern
class SingletonEnforcer{}